import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/team/basketball/lq_team_schedule_logic.dart';
import 'package:ball_lion/entity/team/lq_team_schedule_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class LqTeamScheduleView extends StatefulWidget {
  const LqTeamScheduleView({super.key});

  @override
  State<LqTeamScheduleView> createState() => _LqTeamScheduleViewState();
}

class _LqTeamScheduleViewState extends State<LqTeamScheduleView>
    with AutomaticKeepAliveClientMixin {
  final LqTeamScheduleLogic logic = Get.put(LqTeamScheduleLogic());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<LqTeamScheduleLogic>(initState: (state) async {
      await logic.requestYears();
      await logic.requestData();
      Future.delayed(const Duration(milliseconds: 500))
          .then((value) => logic.initObserver());
    }, builder: (controller) {
      return LoadingWidget<bool>(
        isLoading: controller.years == null,
        data: controller.years?.length == 0,
        child: () => Container(
          color: Colours.greyF7,
          child: Column(
            children: [
              if (controller.years.hasValue) _pageChoice(),
              Expanded(
                  child: LoadingWidget<bool>(
                isLoading: controller.matchGroup == null,
                data: controller.matchGroup?.length,
                child: () => MediaQuery.removePadding(
                  context: context,
                  removeTop: true,
                  child: controller.matchGroup?.length == 0
                      ? const NoDataWidget()
                      : ListView(
                          controller: logic.scrollC,
                          physics: const ClampingScrollPhysics(),
                          children: List.generate(
                              controller.matchGroup?.length ?? 0,
                              (index) => _listItem(index).paddingOnly(
                                  bottom:
                                      controller.matchGroup?.length == index + 1
                                          ? 50
                                          : 0))),
                ),
                // ),
              ))
            ],
          ),
        ),
      );
    });
  }

  Widget _pageChoice() {
    return Container(
      color: Colours.white,
      padding: const EdgeInsets.only(left: 12, right: 8, top: 5, bottom: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () async {
              await logic.showDatePicker();
              await logic.requestData();
              await Future.delayed(const Duration(microseconds: 500)).then(
                  (value) => logic.observerController.jumpTo(
                      index: logic.years?[logic.yearIndex].year.toString() ==
                              DateTime.now().formatedString('yyyy')
                          ? logic.data?.matchGroup?.indexWhere((element) =>
                                  element.title ==
                                  DateTime.now().formatedString('yyyy-MM')) ??
                              0
                          : (logic.data?.matchGroup?.length ?? 1) - 1));
            },
            child: Container(
              height: 24,
              width: 58,
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 6, right: 2),
              decoration: BoxDecoration(
                  color: Colours.greyF5F7FA,
                  borderRadius: BorderRadius.circular(15)),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    QsText(logic.years?[logic.yearIndex].year ?? '',
                        needCenter: true, fontSize: 12),
                    const SizedBox(width: 2),
                    Padding(
                      padding: const EdgeInsets.only(top: 2),
                      child: Image.asset(
                        Utils.getImgPath('down_arrow.png'),
                        width: 8,
                        height: 6,
                      ),
                    )
                  ]),
            ),
          ),
          Container(width: 5),
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                    logic.typeList?.length ?? 0,
                    (childIndex) => logic.typeList?[childIndex].leagueName !=
                            null
                        ? Flexible(
                            flex: 1,
                            child: GestureDetector(
                              onTap: () async {
                                logic.getType(childIndex);
                              },
                              child: Container(
                                height: 24,
                                alignment: Alignment.center,
                                padding:
                                    const EdgeInsets.symmetric(horizontal: 15),
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(30),
                                    color: logic.typeIndex == childIndex
                                        ? Colours.main
                                        : Colours.white),
                                child: QsText(
                                    logic.typeList?[childIndex].leagueName ??
                                        "",
                                    color: logic.typeIndex == childIndex
                                        ? Colours.white
                                        : Colours.grey66,
                                    needCenter: true),
                              ),
                            ),
                          )
                        : Container()),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _listItem(itemIndex) {
    return Container(
      margin: const EdgeInsets.only(top: 10, left: 12, right: 12),
      decoration: BoxDecoration(
          color: Colours.white, borderRadius: BorderRadius.circular(8)),
      child: Padding(
        padding: const EdgeInsets.only(bottom: 8),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
                width: Get.width,
                height: 38,
                alignment: Alignment.center,
                child: QsText(
                    "${(logic.matchGroup?[itemIndex].title ?? "").split('-').join('年')}月",
                    fontSize: 13,
                    fontWeight: FontWeight.w500)),
            Column(
              children: List.generate(
                  logic.matchGroup?[itemIndex].matchArray?.length ?? 0,
                  (index) => _childItem(
                      logic.matchGroup?[itemIndex].matchArray?[index])),
            )
          ],
        ),
      ),
    );
  }

  Widget _childItem(MatchArray? entity) {
    return GestureDetector(
      onTap: () =>
          Get.toNamed(Routes.lqMatchDetail, arguments: entity?.matchId.toInt()),
      child: Stack(
        children: [
          SizedBox(
            height: 50,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(width: 16),
                SizedBox(
                  width: 74,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      QsText(entity?.matchTime ?? "-",
                          fontSize: 12, color: Colours.grey666666),
                      DefaultTextStyle(
                        style: const TextStyle(
                            color: Colours.grey99, fontSize: 10),
                        softWrap: true,
                        overflow: TextOverflow.ellipsis,
                        child: Row(
                          children: [
                            if (entity?.leagueName != null &&
                                entity?.leagueName != '')
                              QsText("${entity!.leagueName}"),
                            if (entity?.kindName != null &&
                                entity?.kindName != '')
                              QsText("\u2000${entity!.kindName!}")
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Container(width: 5),
                Expanded(
                    child: Container(
                  alignment: Alignment.centerRight,
                  child: QsText(entity?.guestName ?? "-",
                      fontSize: 13, maxLines: 2, textAlign: TextAlign.end),
                )),
                Container(
                  width: 66,
                  alignment: Alignment.center,
                  child: QsText(logic.formScore(1, entity),
                      fontSize: 15, fontWeight: FontWeight.w500),
                ),
                // Padding(
                //   padding: const EdgeInsets.only(right: 6),
                //   child: Container(
                //     width: 21,
                //     height: 21,
                //     decoration: const BoxDecoration(shape: BoxShape.circle),
                //     child: CachedNetworkImage(
                //         placeholder: (context, url) => Styles.placeholderIcon(),
                //         errorWidget: (context, url, error) =>
                //             Image.asset(Utils.getImgPath("lq_placeholder.png")),
                //         imageUrl: entity?.homeLogo ?? ''),
                //   ),
                // ),
                Expanded(
                    child: Container(
                  alignment: Alignment.centerLeft,
                  child: QsText(entity?.homeName ?? '-',
                      fontSize: 13, maxLines: 2, textAlign: TextAlign.start),
                )),
                Container(width: 10)
              ],
            ),
          ),
          if (entity?.matchResult != null)
            Positioned(
                right: 0,
                top: 18,
                child: Container(
                    height: 14,
                    width: 14,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        borderRadius: const BorderRadius.only(
                            bottomLeft: Radius.circular(2),
                            topRight: Radius.circular(2)),
                        color: entity?.matchResult == 1
                            ? Colours.redF13333
                            : Colours.green),
                    child: QsText(entity?.matchResult == 1 ? "胜" : "负",
                        fontSize: 10, color: Colors.white)))
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
